package com.pig.openg1.graphics;

import android.content.Context;
import android.opengl.GLES20;
import android.opengl.GLSurfaceView;
import android.opengl.Matrix;
import android.util.Log;

import com.pig.openg1.data.EarthCalculation;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

public class BallRender implements GLSurfaceView.Renderer {

    private Context mContext;
    private EarthCalculation mData;

    private int eAngle = 0;

    public BallRender(Context mContext)
    {
        this.mContext = mContext;
    }

    @Override
    public void onSurfaceCreated(GL10 gl, EGLConfig config) {

        GLES20.glClearColor(0,0,0,1);
        //创建函数，绘制当前的球形
        mData = new EarthCalculation(mContext);
        GLES20.glEnable(GLES20.GL_DEPTH_TEST);
        //初始化矩阵
        mData.init();
    }

    @Override
    public void onSurfaceChanged(GL10 gl, int width, int height) {

        GLES20.glViewport(0,0,width,height);
        float ratio = (float)width/height;
        Matrix.frustumM(mData.mProjMatrix,0,-ratio,ratio,-1,1,4,100);
//        Matrix.setLookAtM(mData.mViewMatrix,0,0,0,7.2f,0,0,0,
//                0,1,0);
        EarthCalculation.onUpdateCamera(new float[] {0,0,7.2f});
        GLES20.glEnable(GLES20.GL_CULL_FACE);
        //初始化当前的纹理
        mData.onLoadTexture();
        EarthCalculation.onUpdateLightLocation(new float[]{100,5,0});
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true)
                {
                    eAngle = (eAngle + 2) %360;
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
//                        e.printStackTrace();
                        Log.e("BallRender","旋转的当前的角度失败！"+ e.getMessage());
                    }
                }
            }
        }).start();
    }

    @Override
    public void onDrawFrame(GL10 gl) {

        GLES20.glClear(GLES20.GL_DEPTH_BUFFER_BIT| GLES20.GL_COLOR_BUFFER_BIT);
        mData.onUpdateAngle(eAngle,0,1,0);
        mData.drawSelf();
    }
}
